package com.xinghou.platform.server.api.bussiness.impl;

import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.entity.req.ListReq;
import com.xinghou.platform.entity.req.MsgInfoReq;
import com.xinghou.platform.entity.req.ShareInfoReq;
import com.xinghou.platform.entity.resp.ShareInfoPhotoResp;
import com.xinghou.platform.entity.resp.ShareInfoResp;
import com.xinghou.platform.lucene.main.SharedCardLuceneService;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.api.bussiness.*;
import com.xinghou.platform.server.api.common.Constants;
import com.xinghou.platform.server.api.common.ImageComb;
import com.xinghou.platform.server.api.common.MessageContants;
import com.xinghou.platform.server.api.service.SharedCardLuceneApiService;
import com.xinghou.platform.server.api.service.StoreLuceneApiService;
import com.xinghou.platform.server.mq.MqMessage;
import com.xinghou.platform.service.main.NoticeService;
import com.xinghou.platform.service.main.UserRelationService;
import com.xinghou.platform.util.*;
import com.xinghou.platform.util.exception.DBExceptionEnums;
import com.xinghou.platform.util.exception.ServiceException;
import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("shareInfoService")
public class ShareInfoBusinessServiceImpl implements ShareInfoBusinessService {

/*    private List<ShareInfoResp> shareInfoResplist;*/
    private String photouri = ConfigUtil.getProperty("file_download");
    private String photominuri = ConfigUtil.getProperty("file_download");
    private static String shopurl = ConfigUtil.getProperty("shopimage_download");

    @Resource
    private SharedCardDAO sharedCardDAO;

    @Resource
    private NoticeDAO noticeDAO;

    @Resource
    private NoticeService noticeService;

    @Resource
    private FavoriteDAO favoriteDAO;

    @Resource
    public JiGuangPushService jiGuangPushService;

    @Resource
    private SharedCardPraiseDAO sharedCardPraiseDAO;

    @Resource
    private SharedCardImageDAO sharedCardImageDAO;

    @Resource
    private SharedCardBrowseDAO sharedCardBrowseDAO;

    @Resource
    private StoreService storeService;

    @Resource
    private SharedCardLuceneService sharedCardLuceneService;

    @Resource
    private CardUseAreaService cardUseAreaService;


    @Resource
    private UserDAO userDAO;

    @Resource
    private PhotoDAO photoDAO;

    @Resource
    private StoreDAO storeDAO;

    @Resource
    private StoreImageDAO storeImageDAO;

    @Resource
    private InterestTagsDAO interestTagsDAO;

    @Resource
    private UserRelationFromDAO userRelationFromDAO;

    @Resource
    private UserRelationToDAO userRelationToDAO;

    @Resource
    private StoreBrowseDAO storeBrowseDAO;

    @Resource
    private UserRelationService userRelationService;

    @Resource
    private UserInfoBusinessService userInfoBusinessService;


    @Resource
    private SharedCardLuceneApiService sharedCardLuceneApiService;

    @Resource
    private StoreLuceneApiService storeLuceneApiService;

    @Resource
    private UserStatisticsDAO userStatisticsDAO;

    @Resource
    private VisitFromDAO visitFromDAO;

    @Resource
    private VisitToDAO visitToDAO;
    @Resource
    private UserGeoDAO userGeoDAO;
    @Resource
    private CityDAO cityDAO;
    @Resource
    private DataConfigDAO dataConfigDAO;

    /**
     * 新增分享卡信息 返回shareid
     */
    public int addShareCard(ShareInfoReq shareInfoReq) {
        userInfoBusinessService.checkclosureByUserId(shareInfoReq.getUserid());
        SharedCard sharedCard = new SharedCard();
        sharedCard.setUserid(Integer.valueOf(shareInfoReq.getUserid()));
        sharedCard.setUsearea(shareInfoReq.getUsearea());
        sharedCard.setOperator(shareInfoReq.getOperator());
        if(StringUtils.isBlank(shareInfoReq.getIsreal())){
            sharedCard.setIsreal(1);
        }else{
            sharedCard.setIsreal(Integer.parseInt(shareInfoReq.getIsreal()));
        }
        sharedCard.setContent(shareInfoReq.getCardcontent());
        sharedCard.setUrls(shareInfoReq.getUrls());
        if (!StringUtils.isEmpty(shareInfoReq.getShopid())) {
            sharedCard.setStoreid(Integer.valueOf(shareInfoReq.getShopid()));
        }
        if (!StringUtils.isEmpty(shareInfoReq.getShopname()))
            sharedCard.setStorename(shareInfoReq.getShopname());
        if (!StringUtils.isEmpty(shareInfoReq.getShopaddress()))
            sharedCard.setStoreaddress(shareInfoReq.getShopaddress());

        sharedCard.setStatus((short) 1);
        sharedCard.setPraisecount(0);
        sharedCard.setBrowsecount(0);
        if (shareInfoReq.getMoney() != null) {
            sharedCard.setMoney(Double.valueOf(shareInfoReq.getMoney()));
        } else {
            sharedCard.setMoney(0.0);
        }
        if (shareInfoReq.getMinsale() != null) {
            sharedCard.setMinsale(Double.valueOf(shareInfoReq.getMinsale()));
        } else {
            sharedCard.setMinsale(0.0);
        }
        sharedCard.setDiscount(shareInfoReq.getDiscount());
        if (shareInfoReq.getTransactiontype() != null) {
            sharedCard.setTransactiontype(shareInfoReq.getTransactiontype());
        }
        if (shareInfoReq.getBrokerage() != null) {
            sharedCard.setBrokerage(Double.valueOf(shareInfoReq.getBrokerage()));
        } else {
            sharedCard.setBrokerage(0.0);
        }
        User user=userDAO.getUserById(Integer.parseInt(shareInfoReq.getUserid()));
        if(user==null)
            throw new ServiceException(DBExceptionEnums.USER_IS_NULL);
        sharedCard.setCreatetime(System.currentTimeMillis());
       //UserStatistics userStatistics = userStatisticsDAO.getUserStatById(Integer.valueOf(shareInfoReq.getUserid()));
         UserStatistics userStatistics = new UserStatistics();
        userStatistics.setStatid(Integer.valueOf(shareInfoReq.getUserid()));
        if (userStatistics != null) {
            userStatistics.setSharecount(1);
            userStatistics.setUpdatetime(System.currentTimeMillis());
            userStatisticsDAO.updateUserStat(userStatistics);
        }
        sharedCardDAO.saveSharedCard(sharedCard);
        Integer cardid = sharedCard.getCardid();
        if (!StringUtils.isEmpty(shareInfoReq.getShopid()))
            storeService.addShareCountStatstics(Integer.parseInt(shareInfoReq.getShopid()));
        if (!StringUtils.isEmpty(shareInfoReq.getUsearea())) {
            cardUseAreaService.addCardUseArea(cardid, shareInfoReq.getUsearea());
        }
        if (!StringUtils.isEmpty(shareInfoReq.getShopname())) {
            WaitStore waitStore = new WaitStore();
            waitStore.cardid = cardid;
            waitStore.setAddress(shareInfoReq.getShopaddress());
            waitStore.createtime = System.currentTimeMillis();
            waitStore.setStorename(shareInfoReq.getShopname());
            storeDAO.addWaitStore(waitStore);
        }

        mqMessage.sendMessageCard(cardid.toString(), false);
        mqMessage.sendMessageUser(shareInfoReq.getUserid(), true);
        noticeSendCardMessage(shareInfoReq.getUserid() + "",sharedCard.getCardid()+"");

        return cardid;
    }


    public void noticeSendCardMessage(String srcuserid,String cardid) {
        User user = userDAO.getUserById(Integer.parseInt(srcuserid));
        List<UserRelationTo> userRelations = userRelationToDAO.getAllUserRelationToByToUserId(Integer.parseInt(srcuserid));
        HashMap map = new HashMap();
        map.put("messagecode", Constants.MESSAGE_SENDCARD);
        map.put("type", "1");
        map.put("nickname", user.getNickname());
        map.put("headurl", PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
        map.put("userid", user.getUserid());
        map.put("cardid", cardid);
        String json = JsonUtil.toJson(map);
        if (userRelations == null || userRelations.isEmpty())
            return;
        for (int i = 0; i < userRelations.size(); i++) {
            Notice notice = Notice.instance().setTitle("通知").setType(MessageContants.MESSAGE_TYPE).setPlatform(MessageContants.PLATFORM_ALL)
                    .setFrom(MessageContants.FROM_USER).setReceiverId(userRelations.get(i).getFromuserid().toString()).setMessagecode(MessageContants.CARD_MESSAGE_CODE)
                    .setContent(map);
            noticeService.notice(notice);
        }


    }


    /**
     * 更新分享卡信息 0 成功 1失败
     */
    public int updateShareCardState(ShareInfoReq shareInfoReq) {
        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
        if (sharedCard.getUserid().toString().equals(shareInfoReq.getUserid())) {
            sharedCard.setStatus((short) 0);
            try {
                sharedCardLuceneApiService.updateSharedCard(sharedCard);
                SharedCardLocationGeo cardmongo = new SharedCardLocationGeo();
                cardmongo.setCardId(sharedCard.getUserid());
            } catch (Exception e) {
            }

            if (sharedCardDAO.updateSharedCard(sharedCard) > 0) {
                //更新分享卡或晒卡次数
                int uid = sharedCard.getUserid();
                int type = sharedCard.getSharetype();
                //User user = userDAO.getUserById(uid);
                //int statid = user.getStatId();
               UserStatistics userStatisticsbak = userStatisticsDAO.getUserStatById(uid);
            UserStatistics userStatistics = new UserStatistics();
               userStatistics.setStatid(uid);
                //1,卖，2买
                if (type == 1) {
                   /* int saleCount = userStatistics.getSalecount() - 1;
                    if (saleCount < 0) {
                        saleCount = 0;
                    }*/
                    userStatistics.setSalecount(1);
                } else if (type == 2) {
                   /* int buyCount = userStatistics.getBuycount() - 1;
                    if (buyCount < 0) {
                        buyCount = 0;
                    }*/
                    userStatistics.setBuycount(-1);
                    if(userStatisticsbak.getBuycount()<=0){
                        userStatistics.setBuycount(0);
                    }


                }
                userStatistics.setUpdatetime(System.currentTimeMillis());
                userStatisticsDAO.updateUserStat(userStatistics);

                Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());

                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }

    }

    public int updateShareCard(ShareInfoReq shareInfoReq) {
        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
        String storeid = String.valueOf(sharedCard.getStoreid());

            sharedCard.setContent(shareInfoReq.getContent());
        if(!StringUtils.isBlank(shareInfoReq.getShopid())){
            sharedCard.setStoreid(Integer.valueOf(shareInfoReq.getShopid()));
        }
            sharedCard.setOperator(shareInfoReq.getOperator());
            sharedCard.setStorename(shareInfoReq.getShopname());
            sharedCard.setStoreaddress(shareInfoReq.getShopaddress());
            sharedCard.setUrls(shareInfoReq.getUrls());
            if(!StringUtils.isBlank(shareInfoReq.getMoney())){
                sharedCard.setMoney(Double.parseDouble(shareInfoReq.getMoney()));
            }
        if(!StringUtils.isBlank(shareInfoReq.getMinsale())){
            sharedCard.setMinsale(Double.parseDouble(shareInfoReq.getMinsale()));
        }

            sharedCard.setDiscount(shareInfoReq.getDiscount());

        if(!StringUtils.isBlank(shareInfoReq.getUserid())){
            sharedCard.setUserid(Integer.parseInt(shareInfoReq.getUserid()));
        }


            sharedCard.setTransactiontype(shareInfoReq.getTransactiontype());
            if (!StringUtils.isEmpty(shareInfoReq.getUsearea())) {
                cardUseAreaService.addCardUseArea(Integer.valueOf(shareInfoReq.getShareid()), shareInfoReq.getUsearea());
            }
            try {
                sharedCardLuceneApiService.updateSharedCard(sharedCard);
            } catch (Exception e) {
            }
                sharedCardDAO.updateSharedCard(sharedCard);
          /*  if (sharedCardDAO.updateSharedCard(sharedCard) > 0) {
                if (!storeid.equals(shareInfoReq.getShopid())) {
                    Store storeold = storeDAO.getStoreBystoreId(Integer.valueOf(storeid));
                    Store storenew = storeDAO.getStoreBystoreId(Integer.valueOf(shareInfoReq.getShopid()));
                    //1 sell 2buy
                    int count = 0;
                    storeDAO.updateStore(storeold);
                    //添加门店成功消息
                    storeDAO.updateStore(storenew);
                    //添加门店成功消息
                }

                return 0;
            } else {
                return 1;
            }*/


return 1;
    }


    /**
     * 更新分享卡点赞和浏览 0 成功 1失败
     */
    public int updateShareCardCount(ShareInfoReq shareInfoReq) {

        /**
         * counttype	是	1 点赞 2 浏览 type	是	当counttype：1【1点赞 0取消赞 】注：取消赞数量-1 更新该用户对该分享内容的状态 当counttype：2 【1浏览 2浏览列表】
         */
        int praiseCount = 0;

        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
        if (shareInfoReq.getCounttype().equals("1")) {
            //加上唯一判断
            SharedCardPraise sharedCardPraise = sharedCardPraiseDAO.getSharedCardPraiseBytwo(Integer.valueOf(shareInfoReq.getUserid()), Integer.valueOf(shareInfoReq.getShareid()));

            if (sharedCardPraise == null) {
                sharedCardPraise = new SharedCardPraise();
                sharedCardPraise.setUserId(Integer.valueOf(shareInfoReq.getUserid()));
                sharedCardPraise.setCardId(Integer.valueOf(shareInfoReq.getShareid()));
                sharedCardPraise.setCreateTime(System.currentTimeMillis());

                sharedCardPraise.setStatus(Short.valueOf(shareInfoReq.getType()));
                sharedCardPraiseDAO.saveSharedCardPraise(sharedCardPraise);
            } else {
                sharedCardPraise.setStatus(Short.valueOf(shareInfoReq.getType()));
                sharedCardPraiseDAO.updateSharedCardPraise(sharedCardPraise);
            }

            praiseCount = sharedCard.getPraisecount();
            if (shareInfoReq.getType().equals("1")) {
                praiseCount = praiseCount + 1;
            } else {
                praiseCount = praiseCount - 1;
            }
            if (praiseCount < 0)
                praiseCount = 0;

            sharedCard.setPraisecount(praiseCount);
            sharedCardDAO.updateSharedCard(sharedCard);

        }

        if (shareInfoReq.getCounttype().equals("2")) {
            //加上唯一判断
            SharedCardBrowse sharedCardBrowse = sharedCardBrowseDAO.getSharedCardBrowseBytwo(Integer.valueOf(shareInfoReq.getUserid()), Integer.valueOf(shareInfoReq.getShareid()));

            if (sharedCardBrowse == null) {
                sharedCardBrowse = new SharedCardBrowse();
                sharedCardBrowse.setUserId(Integer.valueOf(shareInfoReq.getUserid()));
                sharedCardBrowse.setCardId(Integer.valueOf(shareInfoReq.getShareid()));
                sharedCardBrowse.setCreateTime(System.currentTimeMillis());
                sharedCardBrowse.setUpdateTime(System.currentTimeMillis());
                sharedCardBrowse.setBrowseType(Short.valueOf(shareInfoReq.getType()));

                sharedCardBrowseDAO.saveSharedCardBrowse(sharedCardBrowse);
            } else {
                sharedCardBrowse.setBrowseType(Short.valueOf(shareInfoReq.getType()));
                sharedCardBrowse.setUpdateTime(System.currentTimeMillis());
                sharedCardBrowseDAO.updateSharedCardBrowse(sharedCardBrowse);
            }
            //统计浏览次数
            praiseCount = sharedCard.getBrowsecount();
            praiseCount = praiseCount + 1;
            sharedCard.setBrowsecount(praiseCount);
            sharedCardDAO.updateSharedCard(sharedCard);
        }
        return praiseCount;
    }


    /**
     * 查询分享卡和兴趣圈详情
     */
    public ShareInfoResp getShareInfo(ShareInfoReq shareInfoReq) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        //分享卡
        if (shareInfoReq.getSharetype().equals("1")) {
            SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.parseInt(shareInfoReq.getShareid()));
            shareInfoResp = getSharedCardByshareId(shareInfoReq.getUserid(), sharedCard);

        }

        return shareInfoResp;
    }

    /**
     * 查询分享卡和兴趣圈照片列表
     */
    public List<ShareInfoPhotoResp> getShareInfoPhoto(ShareInfoReq shareInfoReq) {

        List<ShareInfoPhotoResp> shareInfoPhotoRespList = new ArrayList<ShareInfoPhotoResp>();
        //分享卡
        if (shareInfoReq.getSharetype().equals("1") || shareInfoReq.getSharetype().equals("2") || shareInfoReq.getSharetype().equals("3")) {
            shareInfoPhotoRespList = sharedCardImageDAO.getSharedCardImagelist(Integer.valueOf(shareInfoReq.getShareid()));
            if (null == shareInfoPhotoRespList || shareInfoPhotoRespList.size() < 1) {
                ShareInfoPhotoResp sir = new ShareInfoPhotoResp();
                SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
                StoreImage storeImage = storeImageDAO.getStoreImageList(sharedCard.getStoreid(), 999);//取门面图片
                if (storeImage != null) {
                    sir.setPhotoid(storeImage.getImageId().toString());
                    sir.setShareid(sharedCard.getCardid().toString());
                    sir.setSimphotourl(shopurl + storeImage.getUri());
                    sir.setPhotourl(shopurl + storeImage.getUri());
                }
            }
        }
        return shareInfoPhotoRespList;
    }

    @Override
    public void deleteShare(ShareInfoReq shareInfoReq) {
        sharedCardDAO.deleteShare(Integer.parseInt(shareInfoReq.getShareid()),shareInfoReq.getOperator());
        UserStatistics statisticsbak = userStatisticsDAO.getUserStatById(Integer.parseInt(shareInfoReq.getUserid()));
       UserStatistics statistics = new UserStatistics();
        statistics.setStatid(Integer.parseInt(shareInfoReq.getUserid()));
        statistics.setSharecount(-1);
        if(statisticsbak.getSharecount()<=0){
            statistics.setSharecount(0);
        }
        statistics.setUpdatetime(System.currentTimeMillis());
        userStatisticsDAO.updateUserStat(statistics);

        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.parseInt(shareInfoReq.getShareid()));
        if (sharedCard != null && sharedCard.getStoreid() != null && sharedCard.getStoreid() != 0)
            storeService.reduceShareCountStatstics(sharedCard.getStoreid());

        //更新卡状态，置为不可见，删除状态
        mqMessage.sendMessageCard(shareInfoReq.getShareid(), true);

    }

    private ShareInfoResp getSharedCardByshareId(String userid, SharedCard sharedCard) {
        ShareInfoResp resp = getSharedCardByshareId(sharedCard);
        if (StringUtils.isEmpty(userid)) return resp;
        int n = favoriteDAO.hasFavorityCard(Long.parseLong(userid), Long.parseLong(sharedCard.getCardid().toString()));
        resp.setHasfavorite(n + "");
        return resp;


    }

    private ShareInfoResp getSharedCardByshareId(SharedCard sharedCard) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        int str = 0;
        int praiseCount = 0;
        try {
            if (sharedCard != null) {
                str = sharedCard.getCardid();
                shareInfoResp.setShareid(sharedCard.getCardid() + "");
                shareInfoResp.setUserid(sharedCard.getUserid().toString());
                shareInfoResp.setContent(sharedCard.getContent());
                shareInfoResp.setPraisecount(sharedCard.getPraisecount().toString());
                shareInfoResp.setSharetype(sharedCard.getSharetype().toString());
                shareInfoResp.setDate(sharedCard.getCreatetime().toString());
                shareInfoResp.setViewcount(sharedCard.getBrowsecount().toString());
                shareInfoResp.setDiscount(sharedCard.getDiscount());
                shareInfoResp.setMoney(MathUtil.doubleToInit(sharedCard.getMoney()).toString());
                shareInfoResp.setMinsale(MathUtil.doubleToInit(sharedCard.getMinsale()).toString());
                shareInfoResp.setUsearea(sharedCard.getUsearea());
                shareInfoResp.setTransaction(sharedCard.getTransaction().toString());
                shareInfoResp.setTransactiontype(sharedCard.getTransactiontype().toString());
                shareInfoResp.setTransactiontime(sharedCard.getTransactiontime().toString());
                shareInfoResp.setBrokerage(sharedCard.getBrokerage().toString());
                Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
                shareInfoResp.setShopid(store.getId().toString());
                shareInfoResp.setShopname(store.getName());
                shareInfoResp.setStatus(store.getStatus().toString());
                // setUserInfo(shareInfoResp);
                //统计浏览次数
               /* praiseCount = sharedCard.getBrowsecount();
                praiseCount = praiseCount + 1;
                sharedCard.setBrowsecount(praiseCount);
                sharedCardDAO.updateSharedCard(sharedCard);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return shareInfoResp;
    }

    private void setUserInfo(ShareInfoResp shareInfoResp) {
        User user = userDAO.getUserById(Integer.valueOf(shareInfoResp.getUserid()));
        if (user == null) return;
        shareInfoResp.setSex(user.getSex() == null ? "" : user.getSex().toString());
        shareInfoResp.setNickname(user.getNickname());
        shareInfoResp.setAgeyear(user.getAgeyear());
        //shareInfoResp.setHoroscope(Gethoroscope.getConstellation(user.getBirthday()));
        //shareInfoResp.setAge(DateUtils.getAge(user.getBirthday()));
        shareInfoResp.setHeadurl(ImageComb.combHeaderUrl(user.getHeadurl()));
    }


    private List<ShareInfoResp> getsharedCardlist(List<SharedCard> sharedCardlist) {
        List<ShareInfoResp>  shareInfoResplist = new ArrayList<ShareInfoResp>();
        for (SharedCard sharedCard : sharedCardlist) {
            ShareInfoResp shareInfoResp = getSharedCardByshareId(sharedCard);
            shareInfoResplist.add(shareInfoResp);
        }
        return shareInfoResplist;
    }


    private List<ShareInfoResp> getSharedCardlist(Timestamp num, String type) throws DataAccessException {
        return getsharedCardlist(sharedCardDAO.getSharedCardList(num, type, -1, 0));
    }

    public List<ShareInfoResp> getSharedCardlistbyMap(String userid, String type, String frompage, int skip, int distance) throws DataAccessException {
        int limit = skip;
        skip = Integer.valueOf(frompage) + skip;
        User user = userDAO.getUserById(Integer.valueOf(userid));
        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.valueOf(userid));
        List<SharedCard> sharedCardlist = new ArrayList<SharedCard>();
        List<SharedCard> temps = new ArrayList<SharedCard>();
        Double[] pos = new Double[2];

        if (StringUtils.isNotBlank(userGeo.getLongitude().toString()) && StringUtils.isNotBlank(userGeo.getLatitude().toString())) {
            pos[0] = userGeo.getLongitude();
            pos[1] = userGeo.getLatitude();

            Point point = new Point(pos[0], pos[1]);
            try {
                temps = sharedCardLuceneService.getSearchSharedCardsbyGeo(null, Integer.parseInt(frompage), skip, pos[1], pos[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (SharedCard card : temps) {
                sharedCardlist.add(sharedCardDAO.getSharedCardBycardId(card.getCardid()));
            }
        } else {
            City city = cityDAO.getNameByCode(user.getCitycode());
            if (StringUtils.isNotBlank(city.getLongitude().toString()) && StringUtils.isNotBlank(city.getLatitude().toString())) {
                pos[0] = city.getLongitude();
                pos[1] = city.getLatitude();

                Point point = new Point(pos[0], pos[1]);
                try {
                    temps = sharedCardLuceneService.getSearchSharedCardsbyGeo(null, Integer.parseInt(frompage), skip, pos[1], pos[0]);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                for (SharedCard card : temps) {
                    sharedCardlist.add(sharedCardDAO.getSharedCardBycardId(card.getCardid()));
                }
            } else {
                sharedCardlist = null;
            }
        }
        return getsharedCardlist(sharedCardlist);
    }

    private List<ShareInfoResp> getSharedCardlist(Timestamp num, String type, int userid, int ftype) throws DataAccessException {
        if (ftype == 1) {
            return getsharedCardlist(sharedCardDAO.getSharedCardList(num, type, -1, 0));
        } else if (ftype == 2) {
            return getsharedCardlist(sharedCardDAO.getSharedCardList(num, type, userid, 1));
        } else {
            return getsharedCardlist(sharedCardDAO.getSharedCardList(num, type, userid, 0));
        }

    }


    private List<ShareInfoResp> getSharedCardBrowselist(int num, int cardid) {
        List<SharedCardBrowse> SharedCardBrowselist = sharedCardBrowseDAO.getSharedCardBrowse(num, cardid);
        List<ShareInfoResp> shareInfoResplist = new ArrayList<ShareInfoResp>();
        for (SharedCardBrowse sharedCardBrowse : SharedCardBrowselist) {
            ShareInfoResp shareInfoResp = buildShareInfoResp(sharedCardBrowse.getUserId().toString(), sharedCardBrowse.getCreateTime().toString());
            shareInfoResplist.add(shareInfoResp);
        }
        return shareInfoResplist;
    }

    private List<ShareInfoResp> getSharedCardPraiselist(int num, int cardid) {
        List<SharedCardPraise> SharedCardPraiselist = sharedCardPraiseDAO.getSharedCardPraise(num, cardid);
        List<ShareInfoResp>  shareInfoResplist = new ArrayList<ShareInfoResp>();
        for (SharedCardPraise sharedCardPraise : SharedCardPraiselist) {
            ShareInfoResp shareInfoResp = buildShareInfoResp(sharedCardPraise.getUserId().toString(), sharedCardPraise.getCreateTime().toString());
            shareInfoResplist.add(shareInfoResp);
        }
        return shareInfoResplist;
    }


    /**
     * 邻友、手艺人
     */
    private List<ShareInfoResp> getartis(Long num, int userid) {
        List<SharedCard> SharedCardlist = sharedCardDAO.getSharedCard(num, userid);
        List<ShareInfoResp>  shareInfoResplist = new ArrayList<ShareInfoResp>();
        StringBuilder sb = new StringBuilder();
        for (SharedCard sharedCard : SharedCardlist) {
            ShareInfoResp shareInfoResp = new ShareInfoResp();
            shareInfoResp.setUserid(sharedCard.getUserid().toString());

            setUserInfo(shareInfoResp);

            Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
            shareInfoResp.setShopid(store.getId().toString());
            shareInfoResp.setShopname(store.getName());
            List<InterestTags> interestTagslist = interestTagsDAO.getInterestTagsByUserId(sharedCard.getStoreid());
            for (InterestTags interestTags : interestTagslist) {
                sb.append(dataConfigDAO.getDataConfigByTag_id(interestTags.getTagId(), 1).getName());
                for (int i = 0; i < interestTagslist.size(); i++) {
                    sb.append("-");
                }

            }
            shareInfoResp.setTastelist(sb.toString());
            shareInfoResplist.add(shareInfoResp);
        }
        return shareInfoResplist;
    }

    /**
     * 分享信息查询列表（门店、发现、详情都适用）根据Card_id升序排列
     */
    public List<ShareInfoResp> getSharedCardshoplist(Long num, int userid) throws DataAccessException {
        return getsharedCardlist(sharedCardDAO.getSharedCard(num, userid));
    }


    private ShareInfoResp buildShareInfoResp(String userId, String date) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        shareInfoResp.setDate(date);
        shareInfoResp.setUserid(userId);
        setUserInfo(shareInfoResp);
        return shareInfoResp;
    }

    public int getisfollow(String userid, String touserid) {
        UserRelationFrom userRelationFrom = userRelationFromDAO.getUserRelationFromByUserId(Integer.valueOf(userid), Integer.parseInt(touserid));
        UserRelationTo userRelationTo = userRelationToDAO.getUserRelationToByUserId(Integer.valueOf(userid), Integer.parseInt(touserid));
        int result = 0;
        if (userRelationFrom != null) {
            Short fromlike = userRelationFrom.getIsliked();
            if (fromlike == 1) {
                result = 1;
            }
            if (userRelationTo != null) {
                Short tolike = userRelationTo.getIsliked();
                if (fromlike == 1 && tolike == 1) {
                    result = 2;
                } else if (tolike == 1) {
                    result = 3;
                }
            }
        }
        return result;
    }

    public List<ShareInfoResp> getSharedCardForShoplist(ShareInfoReq shareInfoReq) {
        ShareInfoResp shareInfoResp;
        List<ShareInfoResp> shareInfoResps = new ArrayList<ShareInfoResp>();
        Integer pageno = Integer.parseInt(shareInfoReq.getPageno());
        Integer pagesize = Integer.parseInt(shareInfoReq.getPagesize());
        int startno = (pageno - 1) * pagesize;
        List<SharedCard> sharedCards = sharedCardDAO.getSharedCardbyshopid(Integer.valueOf(shareInfoReq.getShopid()), startno, pagesize);
        for (SharedCard sharedCard : sharedCards) {
            shareInfoResp = new ShareInfoResp();
            shareInfoResp.setDiscount(sharedCard.getDiscount());
            shareInfoResp.setMoney(MathUtil.doubleToInit(sharedCard.getMoney()).toString());
            shareInfoResp.setMinsale(MathUtil.doubleToInit(sharedCard.getMinsale()).toString());
            shareInfoResp.setUserid(sharedCard.getUserid().toString());
            shareInfoResp.setThumurl(getSharedCardFirstImage(sharedCard.getUrls()));
            setUserInfo(shareInfoResp);
            Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
            shareInfoResp.setShopid(store.getId().toString());
            shareInfoResp.setShareid(String.valueOf(sharedCard.getCardid()));
            shareInfoResp.setShopname(store.getName());
            shareInfoResp.setContent(sharedCard.getContent());
            shareInfoResp.setDate(sharedCard.getCreatetime().toString());
            shareInfoResps.add(shareInfoResp);
        }
      /*  //最近常看缓存
        int userid = Integer.parseInt(shareInfoReq.getUserid());
        int shopid = Integer.parseInt(shareInfoReq.getShopid());
        sharedCardDAO.addLookStoreList(userid,shopid,System.currentTimeMillis());*/
        return shareInfoResps;
    }


    public String getSharedCardFirstImage(String url)
    {
        if(StringUtils.isEmpty(url))
            return url;
        String [] temp=url.split(",");
        return PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(temp[0]));
    }


    @Override
    public int updateShareShopCount(ShareInfoReq shareInfoReq) {
        int countbrowse = 0;
        //浏览门店
        if (shareInfoReq.getCounttype().equals("2")) {
            StoreBrowse storeBrowse = storeBrowseDAO.getStoreBrowseBytwo(Integer.valueOf(shareInfoReq.getUserid()), Integer.valueOf(shareInfoReq.getShareid()));
            //新增和更新浏览人
            if (storeBrowse == null) {
                storeBrowse = new StoreBrowse();
                storeBrowse.setBrowseType(Short.valueOf(shareInfoReq.getType()));
                storeBrowse.setCreateTime(System.currentTimeMillis());
                storeBrowse.setStoreId(Integer.valueOf(shareInfoReq.getShareid()));
                storeBrowse.setUserId(Integer.valueOf(shareInfoReq.getUserid()));
                storeBrowse.setUpdateTime(System.currentTimeMillis());
                storeBrowseDAO.saveStoreBrowse(storeBrowse);
            } else {
                storeBrowse.setBrowseType(Short.valueOf(shareInfoReq.getType()));
                storeBrowse.setUpdateTime(System.currentTimeMillis());

                storeBrowseDAO.updateStoreBrowse(storeBrowse);
            }

            Store store = storeDAO.getStoreBystoreId(Integer.valueOf(shareInfoReq.getShareid()));
            storeDAO.updateStore(store);
        }
        return countbrowse;
    }

    public void addAttentionMsg(Integer userid, String nickname, Integer touserid, String message) {
        MsgInfoReq req = new MsgInfoReq();
        req.setUserid(userid.toString());
        req.setTouserid(touserid.toString());
        req.setContent(nickname + "关注了你");
        req.setType(MsgInfoReq.MSG_COMMON_TEXT);
        jiGuangPushService.sendUserMessage(req);

    }

    public void addVisitMsg(Integer userid, String nickname, Integer touserid, String message) {
        MsgInfoReq req = new MsgInfoReq();
        req.setUserid(userid.toString());
        req.setTouserid(touserid.toString());
        req.setContent(nickname + "访问了你的个人主页");
        req.setType(MsgInfoReq.MSG_COMMON_TEXT);
        jiGuangPushService.sendUserMessage(req);

    }


    /**
     * 发送关注消息
     */
    public void attentionUserNotify(String srcid, String touid) {
        User user = userDAO.getUserById(Integer.parseInt(srcid));
        HashMap map = new HashMap();
        map.put("nickname", user.getNickname());
        map.put("userid", user.getUserid());
        map.put("headurl", PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
        map.put("messagecode", Constants.MESSAGE_ATTENTION);
        Notice notice = Notice.instance().setTitle("通知").setType(MessageContants.MESSAGE_TYPE).setPlatform(MessageContants.PLATFORM_ALL)
                .setFrom(MessageContants.FROM_USER).setReceiverId(touid).setMessagecode(MessageContants.FOLLOW_MESSAGE_CODE)
                .setContent(map);
        noticeService.notice(notice);
    }

    @Override
    public int saveRelation(ShareInfoReq shareInfoReq) {

        int fromUserid = Integer.valueOf(shareInfoReq.getUserid());        //我的ID
        int toUserid = Integer.valueOf(shareInfoReq.getToUserid());        //我关注的人的ID
        //我关注
        User user = userDAO.getUserById(fromUserid);
        UserRelationFrom userRelationFrom = userRelationFromDAO.getUserRelationFromByUserId(fromUserid, toUserid);
        //关注我(这里的我==我关注的人)
        UserRelationTo userRelationTo = userRelationToDAO.getUserRelationToByUserId(toUserid, fromUserid);
        boolean bool = false;
        String type = shareInfoReq.getType();
        if ("1".equals(type) && userRelationFrom != null && userRelationFrom.getIsliked() == 1)
            throw new ServiceException(DBExceptionEnums.HAS_ATTENTION);
        if ("2".equals(type) && userRelationFrom != null && userRelationFrom.getIsliked() == 0)
            throw new ServiceException(DBExceptionEnums.HAS_CANCELATTENTION);
        if (userRelationFrom == null) {
            userRelationFrom = new UserRelationFrom();
            userRelationFrom.setFromuserid(fromUserid);
            userRelationFrom.setTouserid(toUserid);
            bool = true;
        }
        if (userRelationTo == null) {
            userRelationTo = new UserRelationTo();
            userRelationTo.setFromuserid(fromUserid);
            userRelationTo.setTouserid(toUserid);
            bool = true;
        }
        //关注
        if (shareInfoReq.getType().equals("1")) {
            userRelationFrom.setCreatetime(System.currentTimeMillis());
            userRelationFrom.setIsliked((short) 1);
            userRelationTo.setCreatetime(System.currentTimeMillis());
            userRelationTo.setIsliked((short) 1);
            if (bool) {
                userRelationFrom.setIsblocked((short) 0);
                userRelationTo.setIsblocked((short) 0);
                userRelationService.saveUserRelation(userRelationFrom, userRelationTo);
            } else {
                userRelationService.updateUserRelation(userRelationFrom, userRelationTo);
            }
            attentionUserNotify(fromUserid + "", toUserid + "");

        }
        //取消关注
        if (shareInfoReq.getType().equals("2")) {
            userRelationFrom.setIsliked((short) 0);
            userRelationTo.setIsliked((short) 0);
            userRelationService.updateUserRelation(userRelationFrom, userRelationTo);
        }
        //我
       UserStatistics fromUserStatisticsbak = userStatisticsDAO.getUserStatById(fromUserid);
        //我关注的人
       UserStatistics toUserStatisticsbak = userStatisticsDAO.getUserStatById(toUserid);
      //  fromUserStatistics.setAttentioncount(userRelationFromDAO.getFollowCountByUserid(fromUserid));
       // toUserStatistics.setFanscount(userRelationFromDAO.getFansCountByUserid(toUserid));
        UserStatistics fromUserStatistics = new UserStatistics();
        UserStatistics toUserStatistics = new UserStatistics();
        fromUserStatistics.setStatid(fromUserid);
        toUserStatistics.setStatid(toUserid);
        if (shareInfoReq.getType().equals("2")) {
            fromUserStatistics.setAttentioncount(-1);
            toUserStatistics.setFanscount(-1);
            if(fromUserStatisticsbak.getAttentioncount()<=0){
                fromUserStatistics.setAttentioncount(0);
            }
            if(toUserStatisticsbak.getFanscount()<=0){
                toUserStatistics.setFanscount(0);
            }
        }else if (shareInfoReq.getType().equals("1")) {
            fromUserStatistics.setAttentioncount(1);
            toUserStatistics.setFanscount(1);
        }
        fromUserStatistics.setUpdatetime(System.currentTimeMillis());
        toUserStatistics.setUpdatetime(System.currentTimeMillis());
        userStatisticsDAO.updateUserStat(toUserStatistics);
        userStatisticsDAO.updateUserStat(fromUserStatistics);
        int result = userRelationService.getUserRelation(userRelationFrom, userRelationTo);

        return result;
    }

    //屏蔽
    public int saveShields(ShareInfoReq shareInfoReq) {

        int fromUserid = Integer.valueOf(shareInfoReq.getUserid());
        int toUserid = Integer.valueOf(shareInfoReq.getShareid());

        UserRelationFrom userRelationFrom = userRelationFromDAO.getUserRelationFromByUserId(fromUserid, toUserid);
        UserRelationTo userRelationTo = userRelationToDAO.getUserRelationToByUserId(toUserid, fromUserid);

        boolean bool = false;

        if (userRelationFrom == null) {
            userRelationFrom = new UserRelationFrom();
            userRelationFrom.setFromuserid(fromUserid);
            userRelationFrom.setTouserid(toUserid);
            bool = true;
        }

        if (userRelationTo == null) {
            userRelationTo = new UserRelationTo();
            userRelationTo.setFromuserid(fromUserid);
            userRelationTo.setTouserid(toUserid);
            bool = true;
        }

        //屏蔽
        if (shareInfoReq.getType().equals("1")) {

            userRelationFrom.setCreatetime(System.currentTimeMillis());
            userRelationFrom.setIsblocked((short) 1);

            userRelationTo.setCreatetime(System.currentTimeMillis());
            userRelationTo.setIsblocked((short) 1);

            if (bool) {
                userRelationFrom.setIsliked((short) 0);
                userRelationTo.setIsliked((short) 0);
                userRelationService.saveUserRelation(userRelationFrom, userRelationTo);
            } else {
                userRelationService.updateUserRelation(userRelationFrom, userRelationTo);
            }
        }

        //取消屏蔽
        if (shareInfoReq.getType().equals("2")) {

            userRelationFrom.setIsblocked((short) 0);
            userRelationTo.setIsblocked((short) 0);

            userRelationService.updateUserRelation(userRelationFrom, userRelationTo);
        }

        int result = userRelationService.getUserShields(userRelationFrom, userRelationTo);

        return result;
    }


    public int saveVisits(ShareInfoReq shareInfoReq) {


        int fromUserid = Integer.valueOf(shareInfoReq.getUserid());
        int toUserid = Integer.valueOf(shareInfoReq.getToUserid());

        User fromUser=userDAO.getUserById(fromUserid);
        User toUser= userDAO.getUserById(toUserid);
        if(fromUser==null||toUser==null)
            return 0;

        VisitFrom visitFrom = visitFromDAO.getVisitFromByTwoId(fromUserid, toUserid);
        VisitTo visitTo = visitToDAO.getVisitToByTowId(fromUserid, toUserid);

        if (visitFrom == null) {
            visitFrom = new VisitFrom();
            visitFrom.setFromuserid(fromUserid);
            visitFrom.setTouserid(toUserid);
            visitFrom.setCreatetime(System.currentTimeMillis());
            visitFrom.setUpdatetime(System.currentTimeMillis());
            visitFromDAO.saveVisitFrom(visitFrom);
        } else {
            visitFrom.setUpdatetime(System.currentTimeMillis());
            visitFromDAO.updateVisitFrom(visitFrom);
        }

        if (visitTo == null) {
            visitTo = new VisitTo();
            visitTo.setFromuserid(fromUserid);
            visitTo.setTouserid(toUserid);
            visitTo.setCreatetime(System.currentTimeMillis());
            visitTo.setUpdatetime(System.currentTimeMillis());
            visitToDAO.saveVisitTo(visitTo);
        } else {

            visitTo.setUpdatetime(System.currentTimeMillis());
            visitToDAO.updateVisitTo(visitTo);
        }
        // addVisitMsg(fromUserid,fromuser.getNickname(),toUserid,"访问了你的页面");
        //  UserStatistics userStatistics = userStatisticsDAO.getUserStatById(toUserid);
       UserStatistics userStatistics = new UserStatistics();
        userStatistics.setStatid(toUserid);
        if (userStatistics == null) return 0;
        userStatistics.setVisitcount( 1);
        userStatistics.setUpdatetime(System.currentTimeMillis());
        return userStatisticsDAO.updateUserStat(userStatistics);
    }

    @Override
    public List<ShareInfoResp> searchShareList(ShareInfoReq shareInfoReq) {
        SharedCardQueryParam param = new SharedCardQueryParam();
        if (!StringUtils.isEmpty(shareInfoReq.getName()))
            param.setStorename(shareInfoReq.getName());
        if (!StringUtils.isEmpty(shareInfoReq.getMaxdiscount())) {
            param.setMaxdiscount(Double.parseDouble(shareInfoReq.getMaxdiscount()));
        }else{
            param.setMaxdiscount(10.0);
        }
        if (!StringUtils.isEmpty(shareInfoReq.getMindiscount())) {
            param.setMindiscount(Double.parseDouble(shareInfoReq.getMindiscount()));
        }else{
            param.setMindiscount(0.0);
        }
        if (!StringUtils.isEmpty(shareInfoReq.getUsearea()))
            param.setUserarea(shareInfoReq.getUsearea());
        Integer pageno = Integer.parseInt(shareInfoReq.getPageno());
        Integer pagesize = Integer.parseInt(shareInfoReq.getPagesize());
        Integer fromno = (pageno - 1) * pagesize;
        Double distance = 100000000d;
        Double lon = Double.parseDouble(shareInfoReq.getLongitude());
        Double lat = Double.parseDouble(shareInfoReq.getLatitude());
        List<SharedCard> cards = sharedCardLuceneService.queryBySharedCardParam(param, fromno, pagesize, distance, lon, lat);
        List<ShareInfoResp> resps = new ArrayList<ShareInfoResp>();
        if (cards == null || cards.isEmpty()) return resps;
        for (int i = 0; i < cards.size(); i++) {
            ShareInfoResp resp = new ShareInfoResp();
            commSharedNew(cards.get(i), resps);
        }

        return resps;
    }
    //----------------------------------------------NEW----------------------------------------------

    /**
     * 新增分享卡信息 返回shareid
     */
    public int addShareCardNew(ShareInfoReq shareInfoReq) {
        //Status 1
        //Share_type 1卖 2买
        SharedCard sharedCard = new SharedCard();
        sharedCard.setUserid(Integer.valueOf(shareInfoReq.getUserid()));
        sharedCard.setContent(shareInfoReq.getCardcontent());
        sharedCard.setStoreid(Integer.valueOf(shareInfoReq.getShopid()));
        sharedCard.setStatus((short) 1);
        sharedCard.setSharetype(Byte.valueOf(shareInfoReq.getCardtype()));
        sharedCard.setPraisecount(0);
        sharedCard.setBrowsecount(0);
        sharedCard.setDiscount(shareInfoReq.getDiscount());
        sharedCard.setMoney(Double.valueOf(shareInfoReq.getMoney()));
        sharedCard.setMinsale(Double.valueOf(shareInfoReq.getMinsale()));
        sharedCard.setUsearea(shareInfoReq.getUsearea());
        sharedCard.setTransaction(Short.valueOf(shareInfoReq.getTransaction()));
        sharedCard.setTransactiontype(shareInfoReq.getTransactiontype());
        sharedCard.setTransactiontime(shareInfoReq.getTransactiontime());
        sharedCard.setBrokerage(Double.valueOf(shareInfoReq.getBrokerage()));
        sharedCard.setCreatetime(System.currentTimeMillis());

       Store store = storeDAO.getStoreBystoreId(Integer.valueOf(shareInfoReq.getShopid()));
        //  UserStatistics userStatistics = userStatisticsDAO.getUserStatById(Integer.valueOf(shareInfoReq.getUserid()));
            UserStatistics userStatistics = new UserStatistics();
        userStatistics.setStatid(Integer.valueOf(shareInfoReq.getUserid()));
        if (shareInfoReq.getCardtype().equals("1")) {
            userStatistics.setSalecount( 1);
        } else {
            userStatistics.setBuycount(1);
        }
        userStatistics.setUpdatetime(System.currentTimeMillis());
        userStatisticsDAO.updateUserStat(userStatistics);

        storeDAO.updateStore(store);
        Double pos[] = new Double[2];
        pos[0] = store.getLongitude();
        pos[1] = store.getLatitude();
        Integer cardid = sharedCardDAO.saveSharedCard(sharedCard);
        try {
            storeLuceneApiService.updateStore(store);
            sharedCardLuceneApiService.saveSharedCard(sharedCard);
        } catch (Exception e) {
            return cardid;
        }

        return cardid;
    }



    /**
     * @param isstand 是否标准图
     * @param url
     * @return
     */
    public String combPrefix(Boolean isstand, String url) {
        String result = "";
        if (StringUtils.isEmpty(url)) return "";
        String[] urls = url.split(",");
        for (int i = 0; i < urls.length; i++) {
            if (isstand) {
                result = result + (ImageComb.combHeaderUrl(urls[i]));
            } else {
                result = result + PhotoPathUtil.getCard400w300h(ImageComb.combHeaderUrl(urls[i]));
            }
            if (i != urls.length - 1)
                result = result + ",";
        }
        return result;
    }


    private ShareInfoResp getSharedCardByshareIdNew(String userid, SharedCard sharedCard) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        int str = 0;
        int praiseCount = 0;
        try {
            if (sharedCard != null) {
                str = sharedCard.getCardid();
                shareInfoResp.setStatus(String.valueOf(sharedCard.getStatus()));
                shareInfoResp.setShareid(sharedCard.getCardid() + "");
                shareInfoResp.setUserid(sharedCard.getUserid().toString());
                shareInfoResp.setContent(sharedCard.getContent());
                shareInfoResp.setPhotourl(combPrefix(false,sharedCard.getUrls()));
                shareInfoResp.setStandphotourl(combPrefix(true,sharedCard.getUrls()));
                shareInfoResp.setDate(sharedCard.getCreatetime().toString());
                shareInfoResp.setDiscount(sharedCard.getDiscount());
                shareInfoResp.setMoney(sharedCard.getMoney() == null ? "0" : MathUtil.doubleToInit(sharedCard.getMoney()).toString());
                shareInfoResp.setMinsale(sharedCard.getMinsale() == null ? "0" : MathUtil.doubleToInit(sharedCard.getMinsale()).toString());
                shareInfoResp.setBrokerage(sharedCard.getBrokerage().toString());
                shareInfoResp.setTransactiontype(sharedCard.getTransactiontype());
                String userarea = sharedCard.getUsearea();
                shareInfoResp.setUsearea(userarea);
                shareInfoResp.setUseareadesc(getUseAreaTitle(userarea));
                int n = favoriteDAO.hasFavorityCard(Long.parseLong(userid), Long.parseLong(sharedCard.getCardid().toString()));
                shareInfoResp.setHasfavorite(n + "");
                User user = userDAO.getUserById(sharedCard.getUserid());
                if (user != null) {
                    shareInfoResp.setNickname(user.getNickname());
                }
                UserStatistics userStatistics = userStatisticsDAO.getUserStatById(sharedCard.getUserid());
                if (userStatistics != null) {
                    shareInfoResp.setSharecardcount(userStatistics.getSalecount().toString());
                }
                Store store=null;
                if(sharedCard.getStoreid()!=null) {
                     store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
                    if (store != null) {
                        shareInfoResp.setShopid(store.getId().toString());
                        shareInfoResp.setShopaddress(store.getAddress());
                    }
                }else {
                    shareInfoResp.setShopaddress(sharedCard.getStoreaddress());
                    shareInfoResp.setShopname(sharedCard.getStorename());
                }
                if (store!=null&&store.getLongitude() != null && store.getLatitude() != null) {
                    shareInfoResp.setLongitude(store.getLongitude().toString());
                    shareInfoResp.setLatitude(store.getLatitude().toString());

                    shareInfoResp.setShopname(store.getName());


                    //12313
                    //统计浏览次数
                    //  praiseCount = sharedCard.getBrowsecount();
                    //  praiseCount = praiseCount + 1;
                    //sharedCard.setBrowsecount(praiseCount);
                    //  sharedCardDAO.updateSharedCard(sharedCard);
                }
                setUserInfo(shareInfoResp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return shareInfoResp;
    }

    public String getUseAreaTitle(String usearea) {
        String usearr[] = usearea.split("-");
        usearea = "";
        int t = 0;
        for (int i = 0; i < usearr.length; i++) {
            try {
                t = Integer.parseInt(usearr[i]);
            } catch (Exception e) {
                continue;
            }
            DataConfig dataConfig = dataConfigDAO.getDataConfigByTag_id(t, 3);
            if (dataConfig == null) continue;
            ;
            String typename = dataConfig.getName();
            usearea = usearea + typename;
            if (i != usearr.length - 1)
                usearea = usearea + "-";
        }
        return usearea;

    }


    public int updateShareCardNew(ShareInfoReq shareInfoReq) {
        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
        String storeid = String.valueOf(sharedCard.getStoreid());
        if (sharedCard.getUserid().toString().equals(shareInfoReq.getUserid())) {
            sharedCard.setContent(shareInfoReq.getContent());
            sharedCard.setStoreid(Integer.valueOf(shareInfoReq.getShopid()));
            sharedCard.setCreatetime(System.currentTimeMillis());
            sharedCard.setDiscount(shareInfoReq.getDiscount());
            sharedCard.setMoney(Double.valueOf(shareInfoReq.getMoney()));
            sharedCard.setMinsale(Double.valueOf(shareInfoReq.getMinsale().toString()));
            sharedCard.setUsearea(shareInfoReq.getUsearea());
            sharedCard.setTransaction(new Short(shareInfoReq.getTransaction()));
            sharedCard.setTransactiontype(shareInfoReq.getTransactiontype());
            sharedCard.setTransactiontime(shareInfoReq.getTransactiontime().toString());
            sharedCard.setBrokerage(Double.valueOf(shareInfoReq.getBrokerage()));
            String lastid = shareInfoReq.getLastpid();
            if (lastid != null) {
                sharedCard.setLast_pid(Integer.parseInt(lastid));
            }
            try {
                sharedCardLuceneApiService.updateSharedCard(sharedCard);
                SharedCardLocationGeo cardgeo = new SharedCardLocationGeo();
                cardgeo.setCardId(sharedCard.getCardid());
                Store store = storeDAO.getStoreBystoreId(Integer.valueOf(shareInfoReq.getShopid()));
                Double pos[] = new Double[2];
                if (store.getLongitude() != null) {
                    pos[0] = store.getLongitude();
                    pos[1] = store.getLatitude();
                }
                cardgeo.setPos(pos);
                cardgeo.setStoreId(sharedCard.getStoreid());
                cardgeo.setStatus(sharedCard.getStatus() * 1);
                cardgeo.setCreatetime(sharedCard.getCreatetime());
            } catch (Exception e) {
            }

            if (sharedCardDAO.updateSharedCard(sharedCard) > 0) {
                if (!storeid.equals(shareInfoReq.getShopid())) {
                    Store storeold = storeDAO.getStoreBystoreId(Integer.valueOf(storeid));
                    Store storenew = storeDAO.getStoreBystoreId(Integer.valueOf(shareInfoReq.getShopid()));
                    //1 sell 2buy
                    int count = 0;

                    storeDAO.updateStore(storeold);
                    storeDAO.updateStore(storenew);
                }

                return 0;
            } else {
                return 1;
            }

        } else {
            return 1;
        }

    }

    /**
     * 更新分享卡信息 0 成功 1失败
     */
    public int updateShareCardStateNew(ShareInfoReq shareInfoReq) {
        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.valueOf(shareInfoReq.getShareid()));
        if (sharedCard.getUserid().toString().equals(shareInfoReq.getUserid())) {
            sharedCard.setStatus((short) 0);
            try {
                sharedCardLuceneApiService.updateSharedCard(sharedCard);
            } catch (Exception e) {
            }

            if (sharedCardDAO.updateSharedCard(sharedCard) > 0) {
                //更新分享卡或晒卡次数
                int uid = sharedCard.getUserid();
                int type = sharedCard.getSharetype();
                User user = userDAO.getUserById(uid);
                int statid = user.getStatid();
               //UserStatistics userStatistics = userStatisticsDAO.getUserStatById(statid);
                 UserStatistics userStatistics = new UserStatistics();
                userStatistics.setStatid(statid);
                //1,卖，2买
                if (type == 1) {
                    int saleCount = -1;
                    if (saleCount < 0) {
                        saleCount = 0;
                    }
                    userStatistics.setSalecount(saleCount);
                } else if (type == 2) {
                    int buyCount = -1;
                    if (buyCount < 0) {
                        buyCount = 0;
                    }
                    userStatistics.setBuycount(buyCount);

                }
                userStatistics.setUpdatetime(System.currentTimeMillis());
                userStatisticsDAO.updateUserStat(userStatistics);
                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }
    /**
     * 查询分享卡
     */

    public ShareInfoResp getShareInfoNew(ShareInfoReq shareInfoReq) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        //分享卡
        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.parseInt(shareInfoReq.getShareid()));
        shareInfoResp = getSharedCardByshareIdNew(shareInfoReq.getUserid(), sharedCard);

        return shareInfoResp;
    }
    /**
     * 查询分享卡(新)
     * 每次10条
     *
     * @throws Exception
     * @throws DataAccessException
     */
    public List<ShareInfoResp> getShareInfoListNew(ShareInfoReq shareInfoReq, int a) throws DataAccessException, Exception {
        List<ShareInfoResp> shareInfoRespList = new ArrayList<ShareInfoResp>();
        Integer userid = Integer.parseInt(shareInfoReq.getUserid());
        Integer type = Integer.parseInt(shareInfoReq.getType());
        int skip = 0;
        if (userid != null) {
            if (type == 1) {//附近的
                UserGeo userGeo = userGeoDAO.getUserGeoById(userid);
                if (userGeo != null) {
                    if (shareInfoReq.getFromno() != null) {
                        if (Integer.parseInt(shareInfoReq.getFromno()) > 0) {
                            skip = Integer.parseInt(shareInfoReq.getFromno());
                        }
                    }
                    Point point = new Point(userGeo.getLongitude(), userGeo.getLatitude());
                    if (null != shareInfoReq.getLongitude() && null != shareInfoReq.getLatitude() && Double.valueOf(shareInfoReq.getLongitude()) > 0 && Double.valueOf(shareInfoReq.getLatitude()) > 0) {
                        point = new Point(Double.valueOf(shareInfoReq.getLongitude()), Double.valueOf(shareInfoReq.getLatitude()));
                    }
                    List<SharedCard> temps = sharedCardLuceneService.getSearchSharedCardsbyGeo(null, skip, Constants.SHAREDCARDNUM, 150d, point.getY(), point.getX());
                    for (SharedCard card : temps) {
                        ShareInfoResp shareInfoResp = new ShareInfoResp();
                        Integer cardid = card.getCardid();
                        Integer userid2 = card.getUserid();
                        shareInfoResp.setUserid(userid2.toString());
                        shareInfoResp.setShareid(cardid.toString());
                        Integer storeId = card.getStoreid();
                        SharedCardImage sharedCardImage = sharedCardImageDAO.getMinTimeSharedCardImageByCardId(cardid);
                        if (sharedCardImage != null) {
                            String uri = sharedCardImage.getUri();
                            int index = uri.lastIndexOf("/");
                            if (index == -1) {
                                index = uri.lastIndexOf("\\");
                            }
                            if (index != -1) {
                                //shareInfoResp.setSimcardphotourl(photominuri+uri.substring(0,index+1)+"160"+uri.substring(index+1,uri.length()));
                                shareInfoResp.setSimcardphotourl(PhotoPathUtil.getStyle_345w375l(photouri + uri));
                            }
                            shareInfoResp.setCardphotourl(photouri + uri);
                        } else {
                            StoreImage storeImage = storeImageDAO.getStoreImageList(storeId, 999);//取门面图片
                            if (storeImage != null) {
                                shareInfoResp.setSimcardphotourl(shopurl + storeImage.getUri());
                                shareInfoResp.setPhotourl(shopurl + storeImage.getUri());
                            }
                        }
                        Store store=null;
                        if(card.getStoreid()!=null) {
                            store = storeDAO.getStoreBystoreId(card.getStoreid());
                            if (store != null) {
                                shareInfoResp.setShopid(store.getId().toString());
                                shareInfoResp.setShopaddress(store.getAddress());
                            }
                        }else {
                            SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.parseInt(shareInfoReq.getShareid()));
                            shareInfoResp.setShopaddress(sharedCard.getStoreaddress());
                            shareInfoResp.setShopname(sharedCard.getStorename());
                        }
                        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(cardid);
                        if (sharedCard != null) {
                           shareInfoResp.setDiscount(sharedCard.getDiscount());
                            shareInfoResp.setTransactiontype(sharedCard.getTransactiontype());
                            shareInfoResp.setContent(sharedCard.getContent());
                            if (sharedCard.getMoney() != null) {
                                shareInfoResp.setMoney(sharedCard.getMoney().toString());
                            } else {
                                shareInfoResp.setMoney("0");
                            }
                        }
                        if (userGeo.getLatitude() != null && userGeo.getLongitude() != null) {
                            //shareInfoResp.setDistance(GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), pos[0], pos[1], GeohashUtil.GaussSphere.Beijing54));
                            shareInfoResp.setDistance(GeohashUtil.distanceOfTwoPointsTOString(store.getLongitude(), store.getLatitude(), userGeo.getLongitude(), userGeo.getLatitude(), GeohashUtil.GaussSphere.Beijing54));
                        } else {
                            shareInfoResp.setDistance("-1");
                        }
                        shareInfoResp.setFromno(String.valueOf(skip + 10));
                        shareInfoRespList.add(shareInfoResp);
                    }
                }
            } else if (type == 2) {//本人已赞
                Timestamp time = Timestamp.valueOf(DateUtils.getCurDateTime());
                if (!shareInfoReq.getFromno().equals("-1")) {
                    time = Timestamp.valueOf(shareInfoReq.getFromno());
                }
                List<SharedCardPraise> cardpraiselist = sharedCardPraiseDAO.getSharedCardByUserId(Integer.parseInt(shareInfoReq.getUserid()), time, 10);
                for (SharedCardPraise cardpraise : cardpraiselist) {
                    SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(cardpraise.getCardId());
                    commSharedNew(sharedCard, shareInfoRespList);
                    if (shareInfoRespList.size() > 0) {
                        shareInfoRespList.get(shareInfoRespList.size() - 1).setFromno(cardpraise.getCreateTime().toString());
                    }
                }
            } else if (type == 3)//本人的
            {

                Integer pageno = Integer.parseInt(shareInfoReq.getPageno());
                Integer pagesize = Integer.parseInt(shareInfoReq.getPagesize());
                int startno = (pageno - 1) * pagesize;
                int tag =1;
                if(!StringUtils.isBlank(shareInfoReq.getTag())){
                    tag =Integer.parseInt(shareInfoReq.getTag());
                }
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("userid",Integer.parseInt(shareInfoReq.getUserid()));
                map.put("startno",startno);
                map.put("pagesize",15);
                map.put("tag",tag);
                List<SharedCard> cardlist = sharedCardDAO.getSharedCardByUserid(map);
                for (SharedCard sharedCard : cardlist) {
                    commSharedNew(sharedCard, shareInfoRespList);
                }
            }
        }
        return shareInfoRespList;
    }

    @Override
    public int updatSharedCardImage(ShareInfoReq shareInfoReq) {
        String sharetype = shareInfoReq.getSharetype();
        int shareid = Integer.parseInt(shareInfoReq.getShareid());
        if (sharetype.equals("1")) {//分享卡
            SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(shareid);
            if (sharedCard != null) {
                SharedCardImage sharedCardImage = sharedCardImageDAO.getMinTimeSharedCardImageByCardId(shareid);
                if (sharedCardImage != null) {
                    sharedCard.setLast_pid(sharedCardImage.getId());
                    return sharedCardDAO.updateSharedCard(sharedCard);
                }
            }
        }
        return 0;
    }
    //新接口 本人或本人已赞会员卡公共方法
    public void commSharedNew(SharedCard sharedCard, List<ShareInfoResp> shareInfoRespList) {
        ShareInfoResp shareInfoResp = new ShareInfoResp();
        if (sharedCard != null) {
            SharedCard card = sharedCardDAO.getSharedCardBycardId(sharedCard.getCardid());
            if (card == null) return;
            shareInfoResp.setShareid(card.getCardid().toString());
            if (card.getStoreid() != null) {
                shareInfoResp.setShopid(card.getStoreid().toString());
            }
            shareInfoResp.setMoney(MathUtil.doubleToInit(card.getMoney()).toString());
            shareInfoResp.setDiscount(card.getDiscount());
            shareInfoResp.setTransactiontype(card.getTransactiontype());
            shareInfoResp.setContent(card.getContent());
            shareInfoResp.setStatus(String.valueOf(card.getStatus()));
            shareInfoResp.setUserid(card.getUserid().toString());
            shareInfoResp.setMinsale(MathUtil.doubleToInit(card.getMinsale()) + "");
            String[] urls = null;
            if (!StringUtils.isEmpty(card.getUrls())) {
                urls = card.getUrls().split(",");
                shareInfoResp.setThumurl(PhotoPathUtil.getHeader50w50h(ImageComb.comPrefixUrl(urls[0])));
            }
            User user = userDAO.getUserById(sharedCard.getUserid());
            if (user != null) {
                shareInfoResp.setNickname(user.getNickname());
                shareInfoResp.setSex(user.getSex() == null ? "" : user.getSex().toString());
            }
            if (sharedCard.getStoreid() != null) {
                Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
                if (store != null) {
                    shareInfoResp.setShopaddress(store.getAddress());
                    shareInfoResp.setShopname(store.getName());
                    shareInfoResp.setLongitude(store.getLongitude().toString());
                    shareInfoResp.setLatitude(store.getLatitude().toString());
                }
            } else {
                shareInfoResp.setShopname(card.getStorename());
            }
            shareInfoRespList.add(shareInfoResp);
        }

    }

    @Override
    public List<SharedCard> cardList(ListReq listReq){
        List<SharedCard> list =sharedCardDAO.cardList(listReq);
        for(SharedCard sharedCard:list) {
            if(sharedCard.getStoreid()==null){
                SharedCard card1= sharedCardDAO.getSharedCardBycardId(sharedCard.getCardid());
                sharedCard.setStorename(card1.getStorename());
                sharedCard.setStoreaddress(card1.getStoreaddress());
            }
        }
        return  list;
    }



    @Override
    public void cardAudit(ListReq listReq){
        if(!StringUtils.isBlank(listReq.getIds())){
            String idss[] = listReq.getIds().split(",");
            for(int i =0;i<idss.length;i++){
                listReq.setId(idss[i].trim());
                listReq.setTimestamp(String.valueOf(System.currentTimeMillis()));
                sharedCardDAO.cardAudit(listReq);
            }
        }

        //发送审核通过或未通过的推送
    }

    /**
     * 发送用户门店消息到消息中心
     */
    private MqMessage mqMessage = new MqMessage();

    @PreDestroy
    public void destory() {
        System.out.println(System.currentTimeMillis() + "close MqMessage  ：");
        try {
            mqMessage.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}